//
//  HJCPhotoBrowserViewController.swift
//  新浪微博Swift
//
//  Created by 郝俊聪 on 15/5/19.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit
import SVProgressHUD

let photoCellID = "photoCellID"
class HJCPhotoBrowserViewController: UIViewController {
    
    var largeImageURLStr : [String]?
    var selectedIndex : NSIndexPath?
    //MARK:-懒加载
    //约束
    lazy var layout : UICollectionViewFlowLayout = {
            let layout = UICollectionViewFlowLayout()
            layout.minimumInteritemSpacing = 0
            layout.minimumLineSpacing = 0
            layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
            return layout
        }()
    //collectionView
    lazy var collectionView : UICollectionView = {
          let collectionView = UICollectionView(frame:CGRectZero, collectionViewLayout: self.layout)
           return collectionView
        }()
    
    
    
    override func loadView() {
        
        super.loadView()
        
        view.addSubview(self.collectionView)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        //创建两个按钮
        let closeBtn = createBtn("关闭")
        //增加监听
        closeBtn.addTarget(self, action: "clickCloseBtn", forControlEvents: UIControlEvents.TouchUpInside)
        
        let SaveBtn = createBtn("保存")
       
        
        //定义一个约束数组，用于装所有的约束
        var arrayM = [AnyObject]()
        //设置两个按钮的约束
        let constraintsH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[closeBtn(80)]-8-[SaveBtn(80)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["closeBtn":closeBtn,"SaveBtn":SaveBtn])
        //加入数组中
        arrayM+=constraintsH
        
        let constraintsV1 = NSLayoutConstraint.constraintsWithVisualFormat("V:[closeBtn(30)]-20-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["closeBtn":closeBtn])
        let constraintsV2 = NSLayoutConstraint.constraintsWithVisualFormat("V:[SaveBtn(30)]-20-|", options:NSLayoutFormatOptions(0), metrics: nil, views: ["SaveBtn":SaveBtn])
        arrayM+=constraintsV1
        arrayM+=constraintsV2
        
        //添加约束属性到父view
        view.addConstraints(arrayM)
        
        
    }
    
    func clickCloseBtn(){
         dismissViewControllerAnimated(true){
            SVProgressHUD.dismiss()
         }
    
    }

    //创建按钮的方法
    private func createBtn(title:String)->UIButton{
        let btn = UIButton()
        btn.setTitle(title, forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
        btn.layer.cornerRadius = 15
        btn.layer.masksToBounds = true
        btn.backgroundColor = UIColor.blackColor()
        btn.alpha = 0.5
        //禁止autoresizing
        btn.setTranslatesAutoresizingMaskIntoConstraints(false)
        view.addSubview(btn)
        return btn
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //注册cell
        collectionView.registerClass(HJCPhotoBrowserCell.self, forCellWithReuseIdentifier: photoCellID)
        layout.itemSize = view.bounds.size
        collectionView.pagingEnabled = true
        
    }
    

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //布局完成之后重新设置下面的属性
        collectionView.frame = UIScreen.mainScreen().bounds
        layout.itemSize = collectionView.bounds.size
        
        
        //设置默认选中页
        collectionView.scrollToItemAtIndexPath(selectedIndex!, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)

        
    }

}

extension HJCPhotoBrowserViewController : UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return largeImageURLStr?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(photoCellID, forIndexPath: indexPath) as! HJCPhotoBrowserCell
        
        //增加自控制器，防止相应链条断开
        if childViewControllers.count == 0 {
            addChildViewController(cell.photoViewC!)
        }
        
        //取出urlStr
        let urlStr = largeImageURLStr![indexPath.item]
        
        //给下一层控制器赋值
        cell.photoViewC?.imageURL = urlStr
        
        cell.photoViewC?.fatherView =  self.view
        
        weak var weakSelf = self
        cell.photoViewC?.comletion = {
            
            weakSelf!.dismissViewControllerAnimated(true, completion: { () -> Void in
                
            })
        
        }
        
        return cell
        
    }

}

class HJCPhotoBrowserCell : UICollectionViewCell {
    //拥有cell属性
    var photoViewC : HJCPhotoViewController?
    ///重写方法init(frame: CGRect)在创建的是初始化数据
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //加载照片展示控制器
        photoViewC = HJCPhotoViewController()
        
        
        //将照片展示控制器的view赋值给cell
        contentView.addSubview(photoViewC!.view)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
